import os.path

import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from datetime import datetime as datetime_
from tools.framework import get_ui_value
from core.constant import *
from module.static_module.parent.model import AdditionModule

matplotlib.use("Agg")

# 设置字体属性，确保中文正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']  # 指定默认字体为SimHei，这是一个支持中文的字体
plt.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题


class MessageOrderModel(AdditionModule):
    def __init__(self, master):
        super().__init__(master, Module.MessageOrder)
        # 实体类映射视图类变量数据
        self.message_file_ls = []  # 消息文件
        self.hold_time_ls = []  # 持仓时间

        # 映射视图类变量数据默认值
        self.message_file = None
        self.hold_time = None
        # 实体类结构变量
        self.sub_view = None

    def sec_init(self):
        # 实体类映射视图类变量数据
        self.message_file_ls = []  # 消息文件
        self.hold_time_ls = []  # 持仓时间

        from module.addition_module.message_order.view import MessageOrderView
        self.sub_view = MessageOrderView(self)

    def get_ui_params(self):
        # 获取ui界面的相关参数
        values, indices = self.sub_view.auto_layout.get_value(
            LabelMember.MessageFile)
        self.message_file = get_ui_value(values, indices, WidgetCategory.Entry)
        values, indices = self.sub_view.auto_layout.get_value(
            LabelMember.HoldTime)
        self.hold_time = get_ui_value(values, indices, WidgetCategory.Entry)

    def on_ok(self):
        self.get_ui_params()
        # 获取基本信息
        # 获取基本信息
        message_file_path = self.message_file  # 消息文件路径
        hold_time = int(self.hold_time)
        # 读取行情和订单文件
        message_data: pd.DataFrame = self.master.file_manager.read_csv(message_file_path)
        dir_ls = []
        if "buy" in message_data.columns:
            dir_ls.append("buy")
        if "sell" in message_data.columns:
            dir_ls.append("sell")
        if len(dir_ls) == 0:
            raise ValueError("buy,sell字段均不在文件中")
        # 将订单信息加入mk_data
        yield_ls = []
        ori_cash = 100
        for num, (index_o, row) in enumerate(message_data.iterrows()):
            for dir_str in dir_ls:
                if bool(row[dir_str]) and not np.isnan(row[dir_str]):
                    open_price = row[dir_str]
                    try:
                        close_price = message_data.iloc[num+hold_time]["close"]
                    except:
                        continue
                    if dir_str == "buy":
                        rate = round((close_price-open_price)/open_price, 3)
                    elif dir_str == "sell":
                        rate = round((open_price-close_price)/open_price, 3)
                    else:
                        raise ValueError("buy,sell字段均不在文件中，逻辑错误。")
                    yield_ls.append(rate)
                    ori_cash *= rate + 1
        # 生成图片路径
        # 整合新路径
        # 最终文件夹路径
        from tools.framework import gen_result_folder_name  # 避免循环调用
        result_folder = gen_result_folder_name(ResultFolder.FHT_HM)
        # 生成新文件夹
        result_folder_path = os.path.join(self.master.file_manager.result_path, ResultFolder.FHT.value, result_folder)
        # 组合出图片绝对路径
        fig_path = os.path.join(result_folder_path, f"FHT_HM_figure_{hold_time}.png")
        # 给出分析表
        # 计算净值数据
        net_values = [100]
        for y in yield_ls:
            net_values.append(net_values[-1] * (1 + y))

        # 创建子图
        fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(10, 10))

        # 绘制净值数据的图
        ax1.plot(net_values, marker='o', linestyle='-', color='b', label='净值')
        ax1.set_title(f'净值数据-{hold_time}', fontsize=16)
        ax1.set_xlabel('时间', fontsize=14)
        ax1.set_ylabel('净值', fontsize=14)
        ax1.legend()
        ax1.grid(True)

        # 统计上涨和下跌点的数量
        up_points = sum(1 for y in yield_ls if y > 0)
        down_points = sum(1 for y in yield_ls if y < 0)
        total_points = len(yield_ls)
        up_percentage_str = str(round(up_points * 100 / total_points, 2)) + '%'
        cumulative_up_percentage = round(sum(y for y in yield_ls if y > 0), 3)
        cumulative_down_percentage = round(sum(y for y in yield_ls if y < 0), 3)

        # 创建表格数据
        table_data = {
            "指标": ["上涨点数", "下跌点数", "累计订单数", "上涨概率", "累计上涨百分比", "累计下跌百分比"],
            "值": [up_points, down_points, total_points, up_percentage_str, cumulative_up_percentage * 100, cumulative_down_percentage * 100]
        }
        df = pd.DataFrame(table_data)

        # 绘制表格
        ax2.axis("tight")
        ax2.axis("off")

        # 创建表格并设置样式
        table = ax2.table(cellText=df.values, colLabels=df.columns, cellLoc="center", loc="center",
                          bbox=[0.2, 0, 0.6, 1])
        table.auto_set_font_size(False)
        table.set_fontsize(12)
        table.scale(1.2, 1.2)

        # 设置表格样式：单双行不同背景色
        for i, key in enumerate(table.get_celld().keys()):
            cell = table.get_celld()[key]
            cell.set_edgecolor("black")
            if key[0] == 0:
                cell.set_text_props(weight="bold", color="white")
                cell.set_facecolor("gray")
            elif key[0] % 2 == 1:
                cell.set_facecolor("#f0f0f0")
            else:
                cell.set_facecolor("white")

        plt.tight_layout()
        self.master.file_manager.save_mpl_fig(plt, fig_path)
        import webbrowser
        webbrowser.open('file://' + os.path.realpath(fig_path))
        pass
